package supercafe.core;

import supercafe.dataprovider.DataPoster;
import supercafe.defines.IntentAction;
import supercafe.defines.URLs;
import supercafe.more.MainScreen;
import supercafe.more.Profile;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class EditOrderDetailsScreen2 extends MakeOrderDetailsScreen {
	    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tvTitle = (TextView) findViewById(R.id.makeOrderTitle);
        tvTitle.setText("Chỉnh sửa đơn hàng");
        Runnable getListItems = new Runnable(){
            @Override
            public void run() {
            	getListItemsOfTable(tableId);
            }
        };
        Thread thread =  new Thread(null, getListItems, "GetMenuItems-MagentoBackground");
        thread.start();
        adap = new OrderItemAdapter(this, R.layout.list_order_items_row, listItems);
        setListAdapter(adap);
    }
	
	private Runnable notifyAdapter = new Runnable() {
        @Override
        public void run() {
            if(listItems != null && listItems.size() > 0 && adap!=null){
            	adap.notifyDataSetChanged();
            }
        }
    };
        
    private void getListItemsOfTable(int id) {
		// TODO Auto-generated method stub
		dataGetter.execute(URLs.GET_ORDER_OF_TABLE + id);		
	}
        
    @Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		// submit new order
		Log.i("@nhan","click on dialog submit");
		String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
		    	"<order>"+
				"<employee>"+Profile.employeeId+"</employee>"+
				"<table>"+tableId+"</table>";
				xml += "<items>";
		for(int i=0;i<this.listItems.size();i++){
			
				xml += "<item id=\""+this.listItems.get(i).getItemId()+"\">"+
						"<quanlity>"+this.listItems.get(i).getQuanlity()+"</quanlity>"+
						"<note>"+this.listItems.get(i).getNote()+"</note>"+
					"</item>";
		}
		xml += "</items></order>";
		//Toast.makeText(this, xml, Toast.LENGTH_LONG).show();
		dataPoster = new DataPoster(this,this);
		dataPoster.execute(xml,URLs.EDIT_ORDER,"orderXml");
		/*
		while(!dataPoster.isFinished()){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		doFinishPost();
		*/
	}
    
    @Override
    public void onClick(View v) {
    	try{
    		int id = v.getId();
    		switch(id){
    			case R.id.btnGoMenu:
		    		Intent goMenuIntent = new Intent(this, 
		    				MenuItemsScreen2.class);
		    		goMenuIntent.putExtra("menu",(listMenuTypes.get(menuPosition)));
					startActivityForResult(goMenuIntent, IntentAction.GET_MENU_ACTION);
					break;
    			case R.id.btnClearAll:
    				if(listItems.isEmpty()) return;
    				AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("Bạn chắc chắn muốn xóa hết đơn hàng này?")
					       .setCancelable(false)
					       .setPositiveButton("Có", new DialogInterface.OnClickListener() {
					    	   
					           public void onClick(DialogInterface dialog, int id) {
					                EditOrderDetailsScreen2.this.clearCurrentOrder();
					           }
					       })
					       .setNegativeButton("Không", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });
					AlertDialog alert = builder.create();
					alert.show();
    				break;
    			case R.id.btnCancel:
    				Intent returnToTaskScreenIntent = new Intent();
    				setResult(Activity.RESULT_CANCELED, returnToTaskScreenIntent);
    				EditOrderDetailsScreen2.this.finish();
    				break;
    			case R.id.btnSubmit:
    				if(listItems.isEmpty()) return;
    				builder = new AlertDialog.Builder(this);
					builder.setMessage("Bạn chắc chắn muốn sửa đơn hàng này?")
					       .setCancelable(false)
					       .setPositiveButton("Có", this)
					       .setNegativeButton("Không", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					                dialog.cancel();
					           }
					       });
					alert = builder.create();
					alert.show();
    				break;
    		}
    	}catch(Exception e){
    		Log.e("exception-tag",e.getMessage());
    	}
    }

	@Override
	public void doFinishGet() {
		// TODO Auto-generated method stub
			//getting list items finish
		String result = dataGetter.getResponseResult();
		listItems = XMLHandler.getListItems(this,result,listItems);
		runOnUiThread(notifyAdapter);
	}
	
	@Override
	public void doFinishPost() {
		String resultXML = dataPoster.getResponseResult();
		String requestResult = XMLHandler.getMessage(resultXML);
		if(requestResult==null){
			requestResult="Đã sửa đơn hàng thành công";
			// chuyển qua activity MainScreen
			Toast.makeText(this, requestResult, Toast.LENGTH_LONG).show();
			Intent mainScreen = new Intent(this, MainScreen.class);
			startActivity(mainScreen);
			finish();
			return ;
		}
		Toast.makeText(this, requestResult, Toast.LENGTH_LONG).show();
	}
}
